#!/usr/bin/env python3
"""
最小可用原型启动脚本
实现基础的一句话生成旅游规划功能
"""

import os
import sys
import asyncio
import logging
from pathlib import Path

# 添加当前目录到Python路径
sys.path.insert(0, str(Path(__file__).parent))
sys.path.insert(0, str(Path(__file__).parent / "backend"))

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.StreamHandler(),
        logging.FileHandler('minimal_app.log')
    ]
)

logger = logging.getLogger(__name__)

def setup_environment():
    """设置环境变量"""
    # 设置基本环境变量
    os.environ.setdefault('PEXELS_API_KEY', 'uMYqeI26ls0QnybeZmhXrDpCvi2OD9pY3igAAFJXbY8Y4d5RUAfiuOZX')
    os.environ.setdefault('CLOUD_STORAGE_TYPE', 'local')
    os.environ.setdefault('LOCAL_STORAGE_PATH', str(Path(__file__).parent / 'media_storage'))
    os.environ.setdefault('isUsedomainnameaddress', 'false')
    
    # 创建必要的目录
    media_dir = Path(os.environ['LOCAL_STORAGE_PATH'])
    media_dir.mkdir(exist_ok=True)
    
    logger.info("环境配置完成")

def check_dependencies():
    """检查关键依赖"""
    required_modules = [
        'fastapi',
        'uvicorn', 
        'aiohttp',
        'requests',
        'PIL'
    ]
    
    missing = []
    for module in required_modules:
        try:
            if module == 'PIL':
                import PIL
            else:
                __import__(module)
        except ImportError:
            missing.append(module)
    
    if missing:
        logger.error(f"缺少依赖模块: {missing}")
        logger.info("请运行: pip install fastapi uvicorn aiohttp requests pillow")
        return False
    
    logger.info("依赖检查通过")
    return True

async def test_pexels_api():
    """测试Pexels API"""
    try:
        import aiohttp
        
        api_key = os.getenv('PEXELS_API_KEY')
        if not api_key:
            logger.warning("Pexels API密钥未配置")
            return False
        
        url = "https://api.pexels.com/v1/search"
        headers = {"Authorization": api_key}
        params = {"query": "travel", "per_page": 1}
        
        async with aiohttp.ClientSession() as session:
            async with session.get(url, headers=headers, params=params) as response:
                if response.status == 200:
                    data = await response.json()
                    if data.get('photos'):
                        logger.info("✅ Pexels API连接成功")
                        return True
                else:
                    logger.warning(f"Pexels API响应错误: {response.status}")
                    return False
    
    except Exception as e:
        logger.error(f"Pexels API测试失败: {e}")
        return False

def create_minimal_backend():
    """创建最小化后端服务"""
    backend_code = '''
import os
import json
import logging
import asyncio
from typing import List, Dict, Optional
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
import aiohttp
from datetime import datetime

logger = logging.getLogger(__name__)

app = FastAPI(title="最小旅游规划API", version="0.1.0")

# 添加CORS中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

class AlbumRequest(BaseModel):
    user_prompt: str
    user_id: Optional[str] = None
    language: Optional[str] = "zh-CN"

class AlbumResponse(BaseModel):
    success: bool
    message: str
    album: Optional[Dict] = None
    error: Optional[str] = None

class PexelsImageService:
    """Pexels图片搜索服务"""
    
    def __init__(self):
        self.api_key = os.getenv('PEXELS_API_KEY')
    
    async def search_images(self, query: str, count: int = 3) -> List[Dict]:
        """搜索图片"""
        if not self.api_key:
            return self._get_default_images(query, count)
        
        try:
            url = "https://api.pexels.com/v1/search"
            headers = {"Authorization": self.api_key}
            params = {
                "query": query,
                "per_page": min(count, 10),
                "orientation": "landscape"
            }
            
            async with aiohttp.ClientSession() as session:
                async with session.get(url, headers=headers, params=params) as response:
                    if response.status == 200:
                        data = await response.json()
                        images = []
                        
                        for photo in data.get("photos", []):
                            image_info = {
                                "url": photo["src"]["large"],
                                "thumbnail": photo["src"]["medium"],
                                "description": photo.get("alt", query),
                                "photographer": photo["photographer"],
                                "source": "Pexels"
                            }
                            images.append(image_info)
                        
                        return images[:count]
            
            return self._get_default_images(query, count)
            
        except Exception as e:
            logger.error(f"Pexels搜索失败: {e}")
            return self._get_default_images(query, count)
    
    def _get_default_images(self, query: str, count: int) -> List[Dict]:
        """获取默认图片"""
        default_images = [
            {
                "url": "https://images.unsplash.com/photo-1506905925346-21bda4d32df4?w=800",
                "thumbnail": "https://images.unsplash.com/photo-1506905925346-21bda4d32df4?w=400",
                "description": f"{query}相关图片",
                "photographer": "Unsplash",
                "source": "Default"
            }
        ]
        return default_images * count

class MinimalTravelPlanner:
    """最小化旅游规划器"""
    
    def __init__(self):
        self.image_service = PexelsImageService()
    
    async def generate_album(self, user_prompt: str, user_id: str = None) -> Dict:
        """生成旅游相册"""
        try:
            logger.info(f"处理用户请求: {user_prompt}")
            
            # 简单的需求分析
            requirements = self._analyze_prompt(user_prompt)
            
            # 生成景点列表
            attractions = self._generate_attractions(requirements)
            
            # 为每个景点获取图片
            for attraction in attractions:
                images = await self.image_service.search_images(
                    f"{attraction['name']} {requirements.get('destination', '')}", 1
                )
                if images:
                    attraction['image'] = images[0]['url']
                    attraction['images'] = images
            
            # 创建相册
            album = {
                'title': f"{requirements.get('destination', '未知目的地')}之旅",
                'description': f"基于您的需求生成的{requirements.get('destination', '旅游')}规划",
                'destination': requirements.get('destination', ''),
                'attractions': attractions,
                'metadata': {
                    'total_attractions': len(attractions),
                    'estimated_duration': f"{len(attractions) * 2}小时",
                    'difficulty_level': '轻松',
                    'budget_estimate': '中等'
                },
                'created_at': datetime.now().isoformat()
            }
            
            return {
                'success': True,
                'album': album,
                'user_id': user_id or 'anonymous'
            }
            
        except Exception as e:
            logger.error(f"生成相册失败: {e}")
            return {
                'success': False,
                'error': f'生成失败: {str(e)}'
            }
    
    def _analyze_prompt(self, prompt: str) -> Dict:
        """简单的提示词分析"""
        prompt_lower = prompt.lower()
        
        # 提取目的地
        destinations = ['北京', '上海', '广州', '深圳', '杭州', '西安', '成都', '重庆']
        destination = '北京'  # 默认
        for dest in destinations:
            if dest in prompt:
                destination = dest
                break
        
        # 提取兴趣类型
        interests = []
        interest_keywords = {
            '历史': '历史文化',
            '文化': '历史文化', 
            '古迹': '历史文化',
            '自然': '自然风光',
            '风景': '自然风光',
            '美食': '美食购物',
            '购物': '美食购物',
            '现代': '现代建筑',
            '建筑': '现代建筑'
        }
        
        for keyword, interest in interest_keywords.items():
            if keyword in prompt_lower and interest not in interests:
                interests.append(interest)
        
        if not interests:
            interests = ['历史文化']
        
        return {
            'destination': destination,
            'interests': interests,
            'description': prompt
        }
    
    def _generate_attractions(self, requirements: Dict) -> List[Dict]:
        """生成景点列表"""
        destination = requirements.get('destination', '北京')
        interests = requirements.get('interests', ['历史文化'])
        
        # 预定义的景点数据
        attractions_db = {
            '北京': {
                '历史文化': [
                    {'name': '故宫博物院', 'category': '历史文化', 'description': '明清两朝的皇家宫殿，中国古代宫廷建筑之精华'},
                    {'name': '天坛公园', 'category': '历史文化', 'description': '明清皇帝祭天的场所，中国古代建筑的杰作'},
                    {'name': '颐和园', 'category': '历史文化', 'description': '清朝皇家园林，中国古典园林艺术的代表'}
                ],
                '自然风光': [
                    {'name': '香山公园', 'category': '自然风光', 'description': '北京著名的赏红叶胜地'},
                    {'name': '北海公园', 'category': '自然风光', 'description': '中国现存最古老的皇家园林之一'}
                ],
                '现代建筑': [
                    {'name': '鸟巢', 'category': '现代建筑', 'description': '2008年奥运会主体育场'},
                    {'name': '水立方', 'category': '现代建筑', 'description': '2008年奥运会游泳馆'}
                ]
            },
            '上海': {
                '现代建筑': [
                    {'name': '东方明珠塔', 'category': '现代建筑', 'description': '上海的标志性建筑'},
                    {'name': '上海中心大厦', 'category': '现代建筑', 'description': '中国第二高楼'},
                    {'name': '外滩', 'category': '现代建筑', 'description': '万国建筑博览群'}
                ],
                '历史文化': [
                    {'name': '豫园', 'category': '历史文化', 'description': '明代私人花园'},
                    {'name': '上海博物馆', 'category': '历史文化', 'description': '中国古代艺术品收藏'}
                ]
            }
        }
        
        # 获取匹配的景点
        attractions = []
        dest_attractions = attractions_db.get(destination, attractions_db['北京'])
        
        for interest in interests:
            if interest in dest_attractions:
                attractions.extend(dest_attractions[interest][:2])  # 每个兴趣类型最多2个景点
        
        # 如果没有匹配的，使用默认景点
        if not attractions:
            attractions = list(dest_attractions.values())[0][:3]
        
        # 添加基础信息
        for attraction in attractions:
            attraction.update({
                'city': destination,
                'country': '中国',
                'opening_hours': '09:00-17:00',
                'ticket_price': '成人票：60元',
                'booking_method': '现场购票或网上预订'
            })
        
        return attractions[:5]  # 最多5个景点

# 创建服务实例
travel_planner = MinimalTravelPlanner()

@app.get("/")
async def root():
    return {"message": "最小旅游规划API服务正在运行", "version": "0.1.0"}

@app.get("/api/health")
async def health_check():
    return {"status": "healthy", "service": "最小旅游规划API"}

@app.post("/api/generate-album", response_model=AlbumResponse)
async def generate_album(request: AlbumRequest):
    """生成旅游相册"""
    try:
        result = await travel_planner.generate_album(
            request.user_prompt, 
            request.user_id
        )
        
        if result.get('success'):
            return AlbumResponse(
                success=True,
                message="相册生成成功",
                album=result['album']
            )
        else:
            return AlbumResponse(
                success=False,
                message="相册生成失败",
                error=result.get('error', '未知错误')
            )
    
    except Exception as e:
        logger.error(f"API错误: {e}")
        return AlbumResponse(
            success=False,
            message="系统错误",
            error=str(e)
        )

@app.get("/api/config/environment")
async def get_environment_config():
    """获取环境配置"""
    return {
        "success": True,
        "environment": "local",
        "api_base_url": "http://localhost:8001",
        "use_domain_name": False
    }

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8001)
'''
    
    # 写入最小化后端文件
    backend_file = Path("minimal_backend.py")
    with open(backend_file, 'w', encoding='utf-8') as f:
        f.write(backend_code)
    
    logger.info("✅ 最小化后端服务创建成功")
    return backend_file

async def main():
    """主函数"""
    print("🚀 启动最小可用原型")
    print("=" * 50)
    
    # 设置环境
    setup_environment()
    
    # 检查依赖
    if not check_dependencies():
        return
    
    # 测试Pexels API
    print("\n测试Pexels API连接...")
    await test_pexels_api()
    
    # 创建最小化后端
    print("\n创建最小化后端服务...")
    backend_file = create_minimal_backend()
    
    print("\n" + "=" * 50)
    print("✅ 最小可用原型准备完成！")
    print("\n🚀 启动服务:")
    print(f"python {backend_file}")
    print("\n🌐 前端访问:")
    print("打开 album_generator.html")
    print("\n📝 API文档:")
    print("http://localhost:8001/docs")
    
    # 询问是否立即启动
    try:
        response = input("\n是否立即启动后端服务？(Y/n): ")
        if response.lower() != 'n':
            print("\n启动后端服务...")
            import subprocess
            subprocess.run([sys.executable, str(backend_file)])
    except KeyboardInterrupt:
        print("\n👋 再见！")

if __name__ == "__main__":
    asyncio.run(main())
